package com.group11.invite.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group11.common.pojo.Job;
import com.group11.common.pojo.ResponseResult;
import com.group11.common.vo.EnterpriseVo;
import com.group11.invite.domain.JobSend;
import com.group11.invite.service.JobSendService;
import com.group11.invite.service.JobService;
import com.group11.invite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/jobsend")
public class JobSendController {

    @Autowired
    private JobSendService jobSendService;

    @Autowired
    private UserService userService;

    @Autowired
    private JobService jobService;


    @PostMapping("send")
    public ResponseResult<Void> send(@RequestHeader int id, @RequestBody JobSend jobSend){
        try {
            jobSendService.addJobSend(jobSend, id);
            return ResponseResult.SUCCESS;
        } catch (Exception e) {
            return new ResponseResult<>(500, e.getMessage());
        }
    }

    @PostMapping("list")
    public ResponseResult<List<JobSend>> getJobSendList(@RequestHeader int id) {
        ResponseResult<EnterpriseVo> enterpriseById = userService.getEnterpriseById(id);
        if (enterpriseById.getCode() != 200) {
            return new ResponseResult<>(enterpriseById.getCode(), enterpriseById.getMessage());
        }

        int ent_id = enterpriseById.getData().getId();

        ResponseResult<List<Job>> byEntId = jobService.getByEntId(ent_id);
        if (byEntId.getCode() != 200) {
            return new ResponseResult<>(byEntId.getCode(), byEntId.getMessage());
        }

        if (byEntId.getData().isEmpty()) {
            return new ResponseResult<>(500, "企业未发布职位");
        }

        ArrayList<Integer> job_ids = new ArrayList<>();
        byEntId.getData().forEach(item -> job_ids.add(item.getId()));


        QueryWrapper<JobSend> jobSendQueryWrapper = new QueryWrapper<>();
        jobSendQueryWrapper.in("job_id", job_ids);
        return new ResponseResult<>(jobSendService.list(jobSendQueryWrapper));

    }

    @PostMapping("delete")
    public ResponseResult<Void> deleteJobSend(@RequestParam int id) {
        boolean remove = jobSendService.removeById(id);
        if (remove) {
            return ResponseResult.SUCCESS;
        }
        return ResponseResult.FAILED;
    }

    @PostMapping("userSent")
    public ResponseResult<List<JobSend>> userSend(@RequestHeader int id) {
        return new ResponseResult<>(jobSendService.userSend(id));
    }


    @PostMapping("/view")
    public ResponseResult<Void> viewJobSend(@RequestParam int id) {
        if (jobSendService.viewJobSend(id)) {
            return ResponseResult.SUCCESS;
        }
        return ResponseResult.FAILED;
    }


}
